import json
import math
import os
from datetime import datetime

import pandas as pd
import io
from typing import List, Tuple

SITE_CAT_DICT = {
    "6": "前端总控",
    "2": "漏缆直放站",
    "10": "隧道前端",
    "13": "音频监听",
    "14": "环境监测",
    "15": "中心发射塔",
    "1": "发射站点 A",
    "4": "发射站点 B",
    "9": "发射站点 C",
    "7": "发射站点 D",
    "8": "发射站点 E",
    "11": "发射站点 F",
    "12": "发射站点 G",
    "3": "电台前端",
    "5": "天线直放站",
    "16": "发射站点H"
}

SITE_STATUS_DICT = {
    0: "未启用",
    1: "启用",
    2: "待定"
}


def generate_excel_file(site_stats: dict, cluster_stats: List[tuple], site_list: List[dict], file_path: str) -> None:
    """生成Excel报表并保存到指定路径"""
    with pd.ExcelWriter(file_path, engine='xlsxwriter') as writer:
        workbook = writer.book
        worksheet = workbook.add_worksheet('站点报表')

        # 添加一些基本的格式
        header_format = workbook.add_format({
            'bold': True,
            'align': 'center',
            'valign': 'vcenter',
            'border': 1,  # 添加边框
            'border_color': 'black'
        })
        # 普通单元格格式（带边框）
        cell_format = workbook.add_format({
            'border': 1,
            'border_color': 'black'
        })

        # 写入站点统计（新格式）
        headers = ['站点总数', '', '启用站点数', '', '未启用站点数', '']
        values = [
            site_stats['total_sites'], '',
            site_stats['active_sites'], '',
            site_stats['inactive_sites'], ''
        ]
        for col, (header, value) in enumerate(zip(headers, values)):
            if header:  # 只写入非空的标题
                worksheet.write(0, col, header, header_format)
                worksheet.write(0, col + 1, value, cell_format)

        # 写入群组统计数据
        row = 1  # 从第3行开始写入数据
        col = 0
        for i, (cluster_name, site_count) in enumerate(cluster_stats):
            if i > 0 and i % 3 == 0:  # 每三个群组换行
                row += 1
                col = 0
                # 填充空单元格的边框
                for empty_col in range(6):
                    if empty_col not in [col, col + 1]:
                        worksheet.write(row, empty_col, '', cell_format)

            worksheet.write(row, col, cluster_name, header_format)
            worksheet.write(row, col + 1, site_count, cell_format)
            col += 2

        # 计算群组统计部分占用的行数
        cluster_rows = math.ceil(len(cluster_stats) / 3)

        # 写入站点列表（从群组统计后开始）
        site_df = pd.DataFrame(site_list)
        start_row = cluster_rows + 3  # 起始留出一行空行

        # 为空行添加边框
        for c in range(6):
            worksheet.write(start_row - 1, c, '', cell_format)
        site_df.to_excel(writer, sheet_name='站点报表', index=False,
                         startrow=start_row)  # 留出一行空行

        # 调整列宽
        worksheet.set_column('A:G', 15)  # 设置前6列的宽度为15

        # 设置边框样式
        border_format = workbook.add_format({
            'border': 1,  # 设置边框
            'border_color': 'black' # 边框颜色
        })

        # 计算数据区域的结束行和列
        end_row = start_row + len(site_df) + 1  # 结束行
        end_col = len(site_df.columns) - 1   # 结束列（从0开始计数）

        # 为站点列表标题行添加特殊格式
        header_range = f'A{start_row + 1}:{chr(65 + end_col)}{start_row + 1}'
        worksheet.conditional_format(header_range, {
            'type': 'no_blanks',
            'format': header_format
        })

        # 为站点列表数据添加边框
        data_range = f'A{start_row + 2}:{chr(65 + end_col)}{end_row}'
        worksheet.conditional_format(data_range, {
            'type': 'no_blanks',
            'format': border_format
        })


def get_grade_name(grade: int) -> str:
    """获取告警等级名称"""
    grade_dict = {
        0: "离线",
        1: "市电",
        2: "载波",
        3: "音频",
        4: "节目",
        5: "前端",
        6: "环境"
    }
    return grade_dict.get(grade, "未知")

def get_alarm_status_name(status: int) -> str:
    """获取消警状态名称"""
    return "已消警" if status == 0 else "未消警" if status == 1 else "未知"

def get_dispose_status_name(status: int) -> str:
    """获取处理状态名称"""
    return "未处理" if status == 0 else "已处理" if status == 1 else "未知"

def get_eliminate_type_name(type_: int) -> str:
    """获取消警方式名称"""
    type_dict = {1: "手动", 2: "自动", 3: "过期"}
    return type_dict.get(type_, "未知")

def format_timestamp(timestamp: int) -> str:
    """格式化时间戳"""
    if not timestamp:
        return ""
    try:
        return datetime.fromtimestamp(timestamp / 1000).strftime('%Y-%m-%d %H:%M:%S')
    except:
        return ""

def format_duration(duration: int) -> str:
    """格式化持续时间"""
    if not duration:
        return "0小时0分"
    hours = duration // 3600000
    minutes = (duration % 3600000) // 60000
    return f"{hours}小时{minutes}分"

# 读取配置文件
def load_config():
    try:
        config_path = os.path.join(os.path.dirname(__file__), 'config.json')
        with open(config_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"Error loading config: {str(e)}")
        return {"baseUrl": "/wwwroot/zhiheyunv2/api"}  # 默认配置